package com.neu.controller;

import com.alibaba.excel.EasyExcel;
import com.neu.base.PageBean;
import com.neu.base.Result;
import com.neu.entity.User;
import com.neu.entity.security.LoginUser;
import com.neu.service.UserService;
import com.neu.utils.excel.DataListener;
import com.neu.utils.excel.ExcelUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/users")
@Tag(name = "用户管理")
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("/page")
    @Parameters({
            @Parameter(name = "pageNum", description = "页码", required = true),
            @Parameter(name = "pageSize", description = "每页显示数量", required = true)
    })
    @Operation(summary = "分页查询")
    public Result page(@RequestParam Integer pageNum,
                       @RequestParam Integer pageSize){

        PageBean<User> pagelist = userService.pagelist(pageNum, pageSize);
        //如果当前页码值大于总页数，返回最后一页数据
        if (pageNum > pagelist.getTotalPage()) {
            pagelist = userService.pagelist((int)pagelist.getTotalPage(), pageSize);
        }
        return Result.success(pagelist);
    }
    @PostMapping("/add")
    @Operation(summary = "添加用户")
    public Result add(@RequestBody User user){
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> permissions = loginUser.getAuthorityStrings();
        if (!permissions.contains("ROLE_super")||!permissions.contains("ROLE_admin")) {
            return Result.error("无权限添加用户!");
        }
        user.setDelFlag("1");
        user.setCreateId(loginUser.getUsername());
        user.setUpdateId(loginUser.getUsername());
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setRegisterType("0");
        return Result.success(userService.save(user));
    }
    @PostMapping("/search")
    @Operation(summary = "搜索用户")
    public Result search(
            @RequestBody Map map){
        PageBean<User> pagelist =userService.search(map);
        return Result.success(pagelist);
    }

    @PostMapping("/findById")
    @Operation(summary = "根据id查询用户")
    public Result findById(@RequestParam String id){
        return Result.success(userService.getById(id));
    }

    @PostMapping("/update")
    @Operation(summary = "更新用户")
    public Result update(@RequestBody User user){
        return userService.updateInfo(user);
    }

    @PostMapping("/updateStatus")
    @Operation(summary = "更新用户状态")
    public Result updateStatus(@RequestParam String username,
                               @RequestParam String status){
        User user = userService.updateState(username, status);
        return Result.success(userService.getById(user.getUserId()));
    }

    @PostMapping("/delete")
    @Operation(summary = "删除用户")
    public Result delete(@RequestBody User user){
        return Result.success(userService.removeById(user.getUserId()));
    }
    @PostMapping("/deleteBatch")
    @Operation(summary = "批量删除用户")
    public Result deleteBatch(@RequestBody String[] ids){
        return Result.success(userService.removeByIds(Arrays.asList(ids)));
    }
    @GetMapping("/export")
    @Operation(summary = "导出用户信息")
    public void export(HttpServletResponse response){
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> permissions = loginUser.getAuthorityStrings();
        String fileName ="";
        if (!permissions.contains("ROLE_super")) {
            fileName = loginUser.getTenantName()+"用户信息表.xlsx";// 下载时的文件名
        }else{
            fileName = "swpt所有用户信息表.xlsx";// 下载时的文件名
        }
        String sheetName = "用户信息"; // 工作表名称
        List<User> users = userService.all();
        // 调用工具类进行导出
        ExcelUtil.exportExcel(response, fileName, sheetName, User.class, users);
    }
    @PostMapping("/import")
    @Operation(summary = "导入用户信息")
    public Result importUsers(@RequestParam("file") MultipartFile file) {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> permissions = loginUser.getAuthorityStrings();
        if (!permissions.contains("ROLE_super")||!permissions.contains("ROLE_admin")) {
            return Result.error("无权限导入用户!");
        }
        if (file.isEmpty()) {
            return Result.error("上传的文件为空");
        }

        try (InputStream inputStream = file.getInputStream()) {
            // 创建监听器
            DataListener<User> listener = new DataListener<>(new User());

            // 读取 Excel
            EasyExcel.read(inputStream, User.class,listener).sheet().doRead();

            // 获取读取的数据
            List<User> userList = listener.getCachedDataList();
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            String encode = encoder.encode("111");

            for (User user : userList) {
                //生成一个 32 字符的字符串，不含破折号（-）
                String id = UUID.randomUUID().toString().replace("-", "");
                user.setUserId(id);
                user.setPassword(encode);
                // 导入的用户默认为何当前登录用户同一租户
                user.setTenantId(loginUser.getTenantId());
                user.setDefaultRole("ROLE_user");
                user.setRegisterType("0");
                user.setDelFlag("1");
                user.setCreateId(loginUser.getUsername());
                user.setUpdateId(loginUser.getUsername());
                user.setCreateTime(LocalDateTime.now());
                user.setUpdateTime(LocalDateTime.now());
            }

            // 这里可以添加数据验证逻辑
            boolean success = userService.process(userList);
            if(!success){
                return Result.error("导入失败: 用户名不能为空");
            }
            return Result.success("导入成功，导入条数: " + userList.size());
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("导入失败: " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("导入过程中出现错误: " + e.getMessage());
        }
    }
    @PostMapping("/findUserByTenantId")
    @Operation(summary = "根据租户id查询该租户下的用户")
    public Result findUserByTenantId(@RequestBody Map<String, String> map) {
        String tenantId = map.get("tenantId");
        List<User> users = userService.findUserByTenantId(tenantId);
        return Result.success(users);

    }

    @PostMapping("/updatePwd")
    @Operation(summary = "搜索用户")
    public Result updatePwd(@RequestBody Map map){
        String oldPassword = (String) map.get("oldPassword");
        String newPassword = (String) map.get("newPassword");
        String confirmPassword = (String) map.get("confirmPassword");

        return userService.updatePwd(oldPassword, newPassword, confirmPassword);
    }
}
